package com.xfcy.blog.utils;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author 晓风残月Lx
 * @date 2023/5/12 22:59
 */
public class LocalDateTimeUtils {

    /**
     * 相差毫秒
     */
    public static Long durationMills(LocalDateTime startTime, LocalDateTime endTime) {
        Duration duration = Duration.between(startTime, endTime);
        return duration.toMillis();
    }

    /**
     * 根据传来的格式转换为字符串
     * @param pattern
     * @return
     */
    public static String ofPattern(String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(LocalDateTime.now());
    }

    /**
     * 根据传来的格式转换为字符串
     * @param pattern
     * @return
     */
    public static String ofPattern(LocalDateTime localDateTime, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(localDateTime);
    }

    /**
     * date 转化为 localDateTime 让后转化为 String
     *
     * @param date
     * @return
     */
    public static String formate(Date date, String pattern) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return ofPattern(instant.atZone(zoneId).toLocalDateTime(), pattern);
    }

    /**
     * 转化为localDateTime
     * @param date
     * @return
     */
    public static LocalDateTime formateLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

}
